package org.jeecg.modules.controller.medicineOrder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.jeecg.common.modules.doctor.entity.Doctor;
import org.jeecg.common.modules.doctor.service.IDoctorService;
import org.jeecg.common.util.HttpClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableScheduling
@Slf4j
public class SaticScheduleTask1 {
    @Resource
    public IDoctorService doctorService;

    @Scheduled(cron = "0 0 2 * * ?")
    public void intoScheduleTask() {
        System.out.println("-----------------------执行同步东城医生定时任务---------------------------");
        tongbuDoctors();
    }
    public void tongbuDoctors(){
        String time = System.currentTimeMillis()+"";
        String str1 = "bjtswjfe6DF09421EA2F9C78"+ time;

        String signature = DigestUtils.md5Hex(str1);
        String signature1 = DigestUtils.md5Hex(signature).toLowerCase();
        String url = "http://www.bjtsjk.com/api.php/list/5/num/1000";
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.put("appid", Arrays.asList("bjtswjfe"));
        params.put("timestamp", Arrays.asList(time));
        params.put("signature", Arrays.asList(signature1) );
        String keywords = HttpClient.sendPOSTRequest(url, params);

        JSONObject json = JSON.parseObject(keywords);
        String data = json.getString("data");
        JSONArray temp=JSONArray.parseArray(data);
        for(int i=0;i<temp.size();i++){
            JSONObject obj=(JSONObject)temp.get(i);
            System.out.println(obj.getString("title"));
            List<Doctor> doctors = doctorService.list(Wrappers.lambdaQuery(Doctor.class).like(Doctor::getName,obj.getString("title")).eq(Doctor::getStatus,"1"));
            if((doctors!=null&&doctors.size()>1)||doctors == null){
                continue;
            }
            for (Doctor dc:doctors ) {
                dc.setDcId(obj.getString("id"));
            }
            doctorService.saveOrUpdateBatch(doctors);
        }

    }
}
